home *** CD-ROM | disk | FTP | other *** search
/ Enter 2006 September / Enter 09 2006.iso / Internet / SpamExperts Home 1.1 / SpamExperts Home.exe / lib / spamexperts.modules / threading.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2006-07-14  |  23.0 KB  |  872 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """Thread module emulating a subset of Java's threading model."""
  5. import sys as _sys
  6.  
  7. try:
  8.     import thread
  9. except ImportError:
  10.     del _sys.modules[__name__]
  11.     raise 
  12.  
  13. from time import time as _time, sleep as _sleep
  14. from traceback import format_exc as _format_exc
  15. from collections import deque
  16. __all__ = [
  17.     'activeCount',
  18.     'Condition',
  19.     'currentThread',
  20.     'enumerate',
  21.     'Event',
  22.     'Lock',
  23.     'RLock',
  24.     'Semaphore',
  25.     'BoundedSemaphore',
  26.     'Thread',
  27.     'Timer',
  28.     'setprofile',
  29.     'settrace',
  30.     'local']
  31. _start_new_thread = thread.start_new_thread
  32. _allocate_lock = thread.allocate_lock
  33. _get_ident = thread.get_ident
  34. ThreadError = thread.error
  35. del thread
  36. _VERBOSE = False
  37. if __debug__:
  38.     
  39.     class _Verbose(object):
  40.         
  41.         def __init__(self, verbose = None):
  42.             if verbose is None:
  43.                 verbose = _VERBOSE
  44.             
  45.             self._Verbose__verbose = verbose
  46.  
  47.         
  48.         def _note(self, format, *args):
  49.             if self._Verbose__verbose:
  50.                 format = format % args
  51.                 format = '%s: %s\n' % (currentThread().getName(), format)
  52.                 _sys.stderr.write(format)
  53.             
  54.  
  55.  
  56. else:
  57.     
  58.     class _Verbose(object):
  59.         
  60.         def __init__(self, verbose = None):
  61.             pass
  62.  
  63.         
  64.         def _note(self, *args):
  65.             pass
  66.  
  67.  
  68. _profile_hook = None
  69. _trace_hook = None
  70.  
  71. def setprofile(func):
  72.     global _profile_hook
  73.     _profile_hook = func
  74.  
  75.  
  76. def settrace(func):
  77.     global _trace_hook
  78.     _trace_hook = func
  79.  
  80. Lock = _allocate_lock
  81.  
  82. def RLock(*args, **kwargs):
  83.     return _RLock(*args, **kwargs)
  84.  
  85.  
  86. class _RLock(_Verbose):
  87.     
  88.     def __init__(self, verbose = None):
  89.         _Verbose.__init__(self, verbose)
  90.         self._RLock__block = _allocate_lock()
  91.         self._RLock__owner = None
  92.         self._RLock__count = 0
  93.  
  94.     
  95.     def __repr__(self):
  96.         if self._RLock__owner:
  97.             pass
  98.         return '<%s(%s, %d)>' % (self.__class__.__name__, self._RLock__owner.getName(), self._RLock__count)
  99.  
  100.     
  101.     def acquire(self, blocking = 1):
  102.         me = currentThread()
  103.         if self._RLock__owner is me:
  104.             self._RLock__count = self._RLock__count + 1
  105.             if __debug__:
  106.                 self._note('%s.acquire(%s): recursive success', self, blocking)
  107.             
  108.             return 1
  109.         
  110.         rc = self._RLock__block.acquire(blocking)
  111.         if rc:
  112.             self._RLock__owner = me
  113.             self._RLock__count = 1
  114.             if __debug__:
  115.                 self._note('%s.acquire(%s): initial success', self, blocking)
  116.             
  117.         elif __debug__:
  118.             self._note('%s.acquire(%s): failure', self, blocking)
  119.         
  120.         return rc
  121.  
  122.     
  123.     def release(self):
  124.         me = currentThread()
  125.         if not self._RLock__owner is me:
  126.             raise AssertionError, 'release() of un-acquire()d lock'
  127.         self._RLock__count = count = self._RLock__count - 1
  128.         if not count:
  129.             self._RLock__owner = None
  130.             self._RLock__block.release()
  131.             if __debug__:
  132.                 self._note('%s.release(): final release', self)
  133.             
  134.         elif __debug__:
  135.             self._note('%s.release(): non-final release', self)
  136.         
  137.  
  138.     
  139.     def _acquire_restore(self, .2):
  140.         (count, owner) = .2
  141.         self._RLock__block.acquire()
  142.         self._RLock__count = count
  143.         self._RLock__owner = owner
  144.         if __debug__:
  145.             self._note('%s._acquire_restore()', self)
  146.         
  147.  
  148.     
  149.     def _release_save(self):
  150.         if __debug__:
  151.             self._note('%s._release_save()', self)
  152.         
  153.         count = self._RLock__count
  154.         self._RLock__count = 0
  155.         owner = self._RLock__owner
  156.         self._RLock__owner = None
  157.         self._RLock__block.release()
  158.         return (count, owner)
  159.  
  160.     
  161.     def _is_owned(self):
  162.         return self._RLock__owner is currentThread()
  163.  
  164.  
  165.  
  166. def Condition(*args, **kwargs):
  167.     return _Condition(*args, **kwargs)
  168.  
  169.  
  170. class _Condition(_Verbose):
  171.     
  172.     def __init__(self, lock = None, verbose = None):
  173.         _Verbose.__init__(self, verbose)
  174.         if lock is None:
  175.             lock = RLock()
  176.         
  177.         self._Condition__lock = lock
  178.         self.acquire = lock.acquire
  179.         self.release = lock.release
  180.         
  181.         try:
  182.             self._release_save = lock._release_save
  183.         except AttributeError:
  184.             pass
  185.  
  186.         
  187.         try:
  188.             self._acquire_restore = lock._acquire_restore
  189.         except AttributeError:
  190.             pass
  191.  
  192.         
  193.         try:
  194.             self._is_owned = lock._is_owned
  195.         except AttributeError:
  196.             pass
  197.  
  198.         self._Condition__waiters = []
  199.  
  200.     
  201.     def __repr__(self):
  202.         return '<Condition(%s, %d)>' % (self._Condition__lock, len(self._Condition__waiters))
  203.  
  204.     
  205.     def _release_save(self):
  206.         self._Condition__lock.release()
  207.  
  208.     
  209.     def _acquire_restore(self, x):
  210.         self._Condition__lock.acquire()
  211.  
  212.     
  213.     def _is_owned(self):
  214.         if self._Condition__lock.acquire(0):
  215.             self._Condition__lock.release()
  216.             return False
  217.         else:
  218.             return True
  219.  
  220.     
  221.     def wait(self, timeout = None):
  222.         if not self._is_owned():
  223.             raise AssertionError, 'wait() of un-acquire()d lock'
  224.         waiter = _allocate_lock()
  225.         waiter.acquire()
  226.         self._Condition__waiters.append(waiter)
  227.         saved_state = self._release_save()
  228.         
  229.         try:
  230.             if timeout is None:
  231.                 waiter.acquire()
  232.                 if __debug__:
  233.                     self._note('%s.wait(): got it', self)
  234.                 
  235.             else:
  236.                 endtime = _time() + timeout
  237.                 delay = 0.00050000000000000001
  238.                 while True:
  239.                     gotit = waiter.acquire(0)
  240.                     if gotit:
  241.                         break
  242.                     
  243.                     remaining = endtime - _time()
  244.                     if remaining <= 0:
  245.                         break
  246.                     
  247.                     delay = min(delay * 2, remaining, 0.050000000000000003)
  248.                     _sleep(delay)
  249.                 if not gotit:
  250.                     if __debug__:
  251.                         self._note('%s.wait(%s): timed out', self, timeout)
  252.                     
  253.                     
  254.                     try:
  255.                         self._Condition__waiters.remove(waiter)
  256.                     except ValueError:
  257.                         pass
  258.                     except:
  259.                         None<EXCEPTION MATCH>ValueError
  260.                     
  261.  
  262.                 None<EXCEPTION MATCH>ValueError
  263.                 if __debug__:
  264.                     self._note('%s.wait(%s): got it', self, timeout)
  265.                 self._acquire_restore(saved_state)
  266.                 return None
  267.  
  268.  
  269.     
  270.     def notify(self, n = 1):
  271.         if not self._is_owned():
  272.             raise AssertionError, 'notify() of un-acquire()d lock'
  273.         _Condition__waiters = self._Condition__waiters
  274.         waiters = _Condition__waiters[:n]
  275.         if not waiters:
  276.             if __debug__:
  277.                 self._note('%s.notify(): no waiters', self)
  278.             
  279.             return None
  280.         
  281.         if not n != 1 or 's':
  282.             pass
  283.         self._note('%s.notify(): notifying %d waiter%s', self, n, '')
  284.         for waiter in waiters:
  285.             waiter.release()
  286.             
  287.             try:
  288.                 _Condition__waiters.remove(waiter)
  289.             continue
  290.             except ValueError:
  291.                 continue
  292.             
  293.  
  294.         
  295.  
  296.     
  297.     def notifyAll(self):
  298.         self.notify(len(self._Condition__waiters))
  299.  
  300.  
  301.  
  302. def Semaphore(*args, **kwargs):
  303.     return _Semaphore(*args, **kwargs)
  304.  
  305.  
  306. class _Semaphore(_Verbose):
  307.     
  308.     def __init__(self, value = 1, verbose = None):
  309.         if not value >= 0:
  310.             raise AssertionError, 'Semaphore initial value must be >= 0'
  311.         _Verbose.__init__(self, verbose)
  312.         self._Semaphore__cond = Condition(Lock())
  313.         self._Semaphore__value = value
  314.  
  315.     
  316.     def acquire(self, blocking = 1):
  317.         rc = False
  318.         self._Semaphore__cond.acquire()
  319.         while self._Semaphore__value == 0:
  320.             if not blocking:
  321.                 break
  322.             
  323.             if __debug__:
  324.                 self._note('%s.acquire(%s): blocked waiting, value=%s', self, blocking, self._Semaphore__value)
  325.             
  326.             self._Semaphore__cond.wait()
  327.         self._Semaphore__value = self._Semaphore__value - 1
  328.         if __debug__:
  329.             self._note('%s.acquire: success, value=%s', self, self._Semaphore__value)
  330.         
  331.         rc = True
  332.         self._Semaphore__cond.release()
  333.         return rc
  334.  
  335.     
  336.     def release(self):
  337.         self._Semaphore__cond.acquire()
  338.         self._Semaphore__value = self._Semaphore__value + 1
  339.         if __debug__:
  340.             self._note('%s.release: success, value=%s', self, self._Semaphore__value)
  341.         
  342.         self._Semaphore__cond.notify()
  343.         self._Semaphore__cond.release()
  344.  
  345.  
  346.  
  347. def BoundedSemaphore(*args, **kwargs):
  348.     return _BoundedSemaphore(*args, **kwargs)
  349.  
  350.  
  351. class _BoundedSemaphore(_Semaphore):
  352.     '''Semaphore that checks that # releases is <= # acquires'''
  353.     
  354.     def __init__(self, value = 1, verbose = None):
  355.         _Semaphore.__init__(self, value, verbose)
  356.         self._initial_value = value
  357.  
  358.     
  359.     def release(self):
  360.         if self._Semaphore__value >= self._initial_value:
  361.             raise ValueError, 'Semaphore released too many times'
  362.         
  363.         return _Semaphore.release(self)
  364.  
  365.  
  366.  
  367. def Event(*args, **kwargs):
  368.     return _Event(*args, **kwargs)
  369.  
  370.  
  371. class _Event(_Verbose):
  372.     
  373.     def __init__(self, verbose = None):
  374.         _Verbose.__init__(self, verbose)
  375.         self._Event__cond = Condition(Lock())
  376.         self._Event__flag = False
  377.  
  378.     
  379.     def isSet(self):
  380.         return self._Event__flag
  381.  
  382.     
  383.     def set(self):
  384.         self._Event__cond.acquire()
  385.         
  386.         try:
  387.             self._Event__flag = True
  388.             self._Event__cond.notifyAll()
  389.         finally:
  390.             self._Event__cond.release()
  391.  
  392.  
  393.     
  394.     def clear(self):
  395.         self._Event__cond.acquire()
  396.         
  397.         try:
  398.             self._Event__flag = False
  399.         finally:
  400.             self._Event__cond.release()
  401.  
  402.  
  403.     
  404.     def wait(self, timeout = None):
  405.         self._Event__cond.acquire()
  406.         
  407.         try:
  408.             if not self._Event__flag:
  409.                 self._Event__cond.wait(timeout)
  410.         finally:
  411.             self._Event__cond.release()
  412.  
  413.  
  414.  
  415. _counter = 0
  416.  
  417. def _newname(template = 'Thread-%d'):
  418.     global _counter
  419.     _counter = _counter + 1
  420.     return template % _counter
  421.  
  422. _active_limbo_lock = _allocate_lock()
  423. _active = { }
  424. _limbo = { }
  425.  
  426. class Thread(_Verbose):
  427.     __initialized = False
  428.     __exc_info = _sys.exc_info
  429.     
  430.     def __init__(self, group = None, target = None, name = None, args = (), kwargs = { }, verbose = None):
  431.         if not group is None:
  432.             raise AssertionError, 'group argument must be None for now'
  433.         _Verbose.__init__(self, verbose)
  434.         self._Thread__target = target
  435.         if not name:
  436.             pass
  437.         self._Thread__name = str(_newname())
  438.         self._Thread__args = args
  439.         self._Thread__kwargs = kwargs
  440.         self._Thread__daemonic = self._set_daemon()
  441.         self._Thread__started = False
  442.         self._Thread__stopped = False
  443.         self._Thread__block = Condition(Lock())
  444.         self._Thread__initialized = True
  445.         self._Thread__stderr = _sys.stderr
  446.  
  447.     
  448.     def _set_daemon(self):
  449.         return currentThread().isDaemon()
  450.  
  451.     
  452.     def __repr__(self):
  453.         if not self._Thread__initialized:
  454.             raise AssertionError, 'Thread.__init__() was not called'
  455.         status = 'initial'
  456.         if self._Thread__started:
  457.             status = 'started'
  458.         
  459.         if self._Thread__stopped:
  460.             status = 'stopped'
  461.         
  462.         if self._Thread__daemonic:
  463.             status = status + ' daemon'
  464.         
  465.         return '<%s(%s, %s)>' % (self.__class__.__name__, self._Thread__name, status)
  466.  
  467.     
  468.     def start(self):
  469.         if not self._Thread__initialized:
  470.             raise AssertionError, 'Thread.__init__() not called'
  471.         if not not (self._Thread__started):
  472.             raise AssertionError, 'thread already started'
  473.         if __debug__:
  474.             self._note('%s.start(): starting thread', self)
  475.         
  476.         _active_limbo_lock.acquire()
  477.         _limbo[self] = self
  478.         _active_limbo_lock.release()
  479.         _start_new_thread(self._Thread__bootstrap, ())
  480.         self._Thread__started = True
  481.         _sleep(9.9999999999999995e-007)
  482.  
  483.     
  484.     def run(self):
  485.         if self._Thread__target:
  486.             self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
  487.         
  488.  
  489.     
  490.     def __bootstrap(self):
  491.         
  492.         try:
  493.             self._Thread__started = True
  494.             _active_limbo_lock.acquire()
  495.             _active[_get_ident()] = self
  496.             del _limbo[self]
  497.             _active_limbo_lock.release()
  498.             if __debug__:
  499.                 self._note('%s.__bootstrap(): thread started', self)
  500.             
  501.             if _trace_hook:
  502.                 self._note('%s.__bootstrap(): registering trace hook', self)
  503.                 _sys.settrace(_trace_hook)
  504.             
  505.             if _profile_hook:
  506.                 self._note('%s.__bootstrap(): registering profile hook', self)
  507.                 _sys.setprofile(_profile_hook)
  508.             
  509.             
  510.             try:
  511.                 self.run()
  512.             except SystemExit:
  513.                 if __debug__:
  514.                     self._note('%s.__bootstrap(): raised SystemExit', self)
  515.                 
  516.             except:
  517.                 __debug__
  518.                 if __debug__:
  519.                     self._note('%s.__bootstrap(): unhandled exception', self)
  520.                 
  521.                 if _sys:
  522.                     _sys.stderr.write('Exception in thread %s:\n%s\n' % (self.getName(), _format_exc()))
  523.                 else:
  524.                     (exc_type, exc_value, exc_tb) = self._Thread__exc_info()
  525.                     
  526.                     try:
  527.                         print >>self._Thread__stderr, 'Exception in thread ' + self.getName() + ' (most likely raised during interpreter shutdown):'
  528.                         print >>self._Thread__stderr, 'Traceback (most recent call last):'
  529.                         while exc_tb:
  530.                             print >>self._Thread__stderr, '  File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)
  531.                             exc_tb = exc_tb.tb_next
  532.                         print >>self._Thread__stderr, '%s: %s' % (exc_type, exc_value)
  533.                     finally:
  534.                         del exc_type
  535.                         del exc_value
  536.                         del exc_tb
  537.  
  538.  
  539.             if __debug__:
  540.                 self._note('%s.__bootstrap(): normal return', self)
  541.         finally:
  542.             self._Thread__stop()
  543.             
  544.             try:
  545.                 self._Thread__delete()
  546.             except:
  547.                 pass
  548.  
  549.  
  550.  
  551.     
  552.     def __stop(self):
  553.         self._Thread__block.acquire()
  554.         self._Thread__stopped = True
  555.         self._Thread__block.notifyAll()
  556.         self._Thread__block.release()
  557.  
  558.     
  559.     def __delete(self):
  560.         '''Remove current thread from the dict of currently running threads.'''
  561.         _active_limbo_lock.acquire()
  562.         
  563.         try:
  564.             del _active[_get_ident()]
  565.         except KeyError:
  566.             if 'dummy_threading' not in _sys.modules:
  567.                 raise 
  568.             
  569.         except:
  570.             'dummy_threading' not in _sys.modules
  571.         finally:
  572.             _active_limbo_lock.release()
  573.  
  574.  
  575.     
  576.     def join(self, timeout = None):
  577.         if not self._Thread__initialized:
  578.             raise AssertionError, 'Thread.__init__() not called'
  579.         if not self._Thread__started:
  580.             raise AssertionError, 'cannot join thread before it is started'
  581.         if not self is not currentThread():
  582.             raise AssertionError, 'cannot join current thread'
  583.         if __debug__:
  584.             if not self._Thread__stopped:
  585.                 self._note('%s.join(): waiting until thread stops', self)
  586.             
  587.         
  588.         self._Thread__block.acquire()
  589.         
  590.         try:
  591.             if timeout is None:
  592.                 while not self._Thread__stopped:
  593.                     self._Thread__block.wait()
  594.                 if __debug__:
  595.                     self._note('%s.join(): thread stopped', self)
  596.                 
  597.             else:
  598.                 deadline = _time() + timeout
  599.                 while not self._Thread__stopped:
  600.                     delay = deadline - _time()
  601.                     if delay <= 0:
  602.                         if __debug__:
  603.                             self._note('%s.join(): timed out', self)
  604.                         
  605.                         break
  606.                     
  607.                     self._Thread__block.wait(delay)
  608.                 if __debug__:
  609.                     self._note('%s.join(): thread stopped', self)
  610.                 self._Thread__block.release()
  611.                 return None
  612.  
  613.  
  614.     
  615.     def getName(self):
  616.         if not self._Thread__initialized:
  617.             raise AssertionError, 'Thread.__init__() not called'
  618.         return self._Thread__name
  619.  
  620.     
  621.     def setName(self, name):
  622.         if not self._Thread__initialized:
  623.             raise AssertionError, 'Thread.__init__() not called'
  624.         self._Thread__name = str(name)
  625.  
  626.     
  627.     def isAlive(self):
  628.         if not self._Thread__initialized:
  629.             raise AssertionError, 'Thread.__init__() not called'
  630.         if self._Thread__started:
  631.             pass
  632.         return not (self._Thread__stopped)
  633.  
  634.     
  635.     def isDaemon(self):
  636.         if not self._Thread__initialized:
  637.             raise AssertionError, 'Thread.__init__() not called'
  638.         return self._Thread__daemonic
  639.  
  640.     
  641.     def setDaemon(self, daemonic):
  642.         if not self._Thread__initialized:
  643.             raise AssertionError, 'Thread.__init__() not called'
  644.         if not not (self._Thread__started):
  645.             raise AssertionError, 'cannot set daemon status of active thread'
  646.         self._Thread__daemonic = daemonic
  647.  
  648.  
  649.  
  650. def Timer(*args, **kwargs):
  651.     return _Timer(*args, **kwargs)
  652.  
  653.  
  654. class _Timer(Thread):
  655.     """Call a function after a specified number of seconds:
  656.  
  657.     t = Timer(30.0, f, args=[], kwargs={})
  658.     t.start()
  659.     t.cancel() # stop the timer's action if it's still waiting
  660.     """
  661.     
  662.     def __init__(self, interval, function, args = [], kwargs = { }):
  663.         Thread.__init__(self)
  664.         self.interval = interval
  665.         self.function = function
  666.         self.args = args
  667.         self.kwargs = kwargs
  668.         self.finished = Event()
  669.  
  670.     
  671.     def cancel(self):
  672.         """Stop the timer if it hasn't finished yet"""
  673.         self.finished.set()
  674.  
  675.     
  676.     def run(self):
  677.         self.finished.wait(self.interval)
  678.         if not self.finished.isSet():
  679.             self.function(*self.args, **self.kwargs)
  680.         
  681.         self.finished.set()
  682.  
  683.  
  684.  
  685. class _MainThread(Thread):
  686.     
  687.     def __init__(self):
  688.         Thread.__init__(self, name = 'MainThread')
  689.         self._Thread__started = True
  690.         _active_limbo_lock.acquire()
  691.         _active[_get_ident()] = self
  692.         _active_limbo_lock.release()
  693.         import atexit
  694.         atexit.register(self._MainThread__exitfunc)
  695.  
  696.     
  697.     def _set_daemon(self):
  698.         return False
  699.  
  700.     
  701.     def _MainThread__exitfunc(self):
  702.         self._Thread__stop()
  703.         t = _pickSomeNonDaemonThread()
  704.         if t:
  705.             if __debug__:
  706.                 self._note('%s: waiting for other threads', self)
  707.             
  708.         
  709.         while t:
  710.             t.join()
  711.             t = _pickSomeNonDaemonThread()
  712.         if __debug__:
  713.             self._note('%s: exiting', self)
  714.         
  715.         self._Thread__delete()
  716.  
  717.  
  718.  
  719. def _pickSomeNonDaemonThread():
  720.     for t in enumerate():
  721.         if not t.isDaemon() and t.isAlive():
  722.             return t
  723.             continue
  724.     
  725.  
  726.  
  727. class _DummyThread(Thread):
  728.     
  729.     def __init__(self):
  730.         Thread.__init__(self, name = _newname('Dummy-%d'))
  731.         self._Thread__started = True
  732.         _active_limbo_lock.acquire()
  733.         _active[_get_ident()] = self
  734.         _active_limbo_lock.release()
  735.  
  736.     
  737.     def _set_daemon(self):
  738.         return True
  739.  
  740.     
  741.     def join(self, timeout = None):
  742.         if not False:
  743.             raise AssertionError, 'cannot join a dummy thread'
  744.  
  745.  
  746.  
  747. def currentThread():
  748.     
  749.     try:
  750.         return _active[_get_ident()]
  751.     except KeyError:
  752.         return _DummyThread()
  753.  
  754.  
  755.  
  756. def activeCount():
  757.     _active_limbo_lock.acquire()
  758.     count = len(_active) + len(_limbo)
  759.     _active_limbo_lock.release()
  760.     return count
  761.  
  762.  
  763. def enumerate():
  764.     _active_limbo_lock.acquire()
  765.     active = _active.values() + _limbo.values()
  766.     _active_limbo_lock.release()
  767.     return active
  768.  
  769. _MainThread()
  770.  
  771. try:
  772.     from thread import _local as local
  773. except ImportError:
  774.     from _threading_local import local
  775.  
  776.  
  777. def _test():
  778.     
  779.     class BoundedQueue(_Verbose):
  780.         
  781.         def __init__(self, limit):
  782.             _Verbose.__init__(self)
  783.             self.mon = RLock()
  784.             self.rc = Condition(self.mon)
  785.             self.wc = Condition(self.mon)
  786.             self.limit = limit
  787.             self.queue = deque()
  788.  
  789.         
  790.         def put(self, item):
  791.             self.mon.acquire()
  792.             while len(self.queue) >= self.limit:
  793.                 self._note('put(%s): queue full', item)
  794.                 self.wc.wait()
  795.             self.queue.append(item)
  796.             self._note('put(%s): appended, length now %d', item, len(self.queue))
  797.             self.rc.notify()
  798.             self.mon.release()
  799.  
  800.         
  801.         def get(self):
  802.             self.mon.acquire()
  803.             while not self.queue:
  804.                 self._note('get(): queue empty')
  805.                 self.rc.wait()
  806.             item = self.queue.popleft()
  807.             self._note('get(): got %s, %d left', item, len(self.queue))
  808.             self.wc.notify()
  809.             self.mon.release()
  810.             return item
  811.  
  812.  
  813.     
  814.     class ProducerThread(Thread):
  815.         
  816.         def __init__(self, queue, quota):
  817.             Thread.__init__(self, name = 'Producer')
  818.             self.queue = queue
  819.             self.quota = quota
  820.  
  821.         
  822.         def run(self):
  823.             random = random
  824.             import random
  825.             counter = 0
  826.             while counter < self.quota:
  827.                 counter = counter + 1
  828.                 self.queue.put('%s.%d' % (self.getName(), counter))
  829.                 _sleep(random() * 1.0000000000000001e-005)
  830.  
  831.  
  832.     
  833.     class ConsumerThread(Thread):
  834.         
  835.         def __init__(self, queue, count):
  836.             Thread.__init__(self, name = 'Consumer')
  837.             self.queue = queue
  838.             self.count = count
  839.  
  840.         
  841.         def run(self):
  842.             while self.count > 0:
  843.                 item = self.queue.get()
  844.                 print item
  845.                 self.count = self.count - 1
  846.  
  847.  
  848.     NP = 3
  849.     QL = 4
  850.     NI = 5
  851.     Q = BoundedQueue(QL)
  852.     P = []
  853.     for i in range(NP):
  854.         t = ProducerThread(Q, NI)
  855.         t.setName('Producer-%d' % (i + 1))
  856.         P.append(t)
  857.     
  858.     C = ConsumerThread(Q, NI * NP)
  859.     for t in P:
  860.         t.start()
  861.         _sleep(9.9999999999999995e-007)
  862.     
  863.     C.start()
  864.     for t in P:
  865.         t.join()
  866.     
  867.     C.join()
  868.  
  869. if __name__ == '__main__':
  870.     _test()
  871.  
  872.